<?php

function debug($str)
{
	/* echo '<p class="debug">';
	var_dump($str);
	echo '</p>'; */
}

function get_host($url) {
	$host = $url;
	$key = '://';
	$index = strpos($host, $key);
	if ($index !== false) {
		$host = substr($host, $index + strlen($key));
	}
	$key = '/';
	$index = strpos($host, $key);
	if ($index !== false) {
		$host = substr($host, 0, $index);
	}
	return $host;
}
//http://bloggeritems.com/new/vintimes/get
/* mkdir('../imhere', 0755, true);//http://bloggeritems.com/new/iamhere */
/* mkdir('/imhere', 0755, true);//http://bloggeritems.com/iamhere */
/* mkdir('./imhere', 0755, true);//http://bloggeritems.com/vintimes/iamhere */

/* `get options */
$url = $_POST["url"];
$force = $_POST["force"];

/* $url = "http://www.eva.vn/nha-dep/cu-don-gian-la-toi-yeu-c169a123186.html";
$force = "true"; */

/* check that's image or not */ 
if (strpos($url, '.gif') !== false || strpos($url, '.GIF') !== false || 
	strpos($url, '.png') !== false || strpos($url, '.PNG') !== false ||
	strpos($url, '.jpg') !== false || strpos($url, '.JPG') !== false || 
	strpos($url, '.bmp') !== false || strpos($url, '.BMP') !== false ||
	strpos($url, '.jpeg') !== false || strpos($url, '.JPEG') || 
	strpos($url, '/image') !== false || strpos($url, '/Image') !== false) {
	$image = true;
} else {
	$image = false;
}
		
/* `database select */
$cache = mysql_query('SELECT * FROM `wp_cache` WHERE `link`="'.$url.'"');
$cache_rows = mysql_num_rows($cache);
if ($cache_rows > 0) {
	debug('had in database');
	/* `cachable only for image */
	$item = mysql_fetch_assoc($cache);          
	$fullpath = $item['content'];
	mysql_free_result($cache);  
} else {
	debug('nothing in database');
/* `get date-time */
	/* set the default timezone to use. Available since PHP 5.1*/
	date_default_timezone_set('Asia/Ho_Chi_Minh');

	/* Get year and month for media folder name*/
	$dyear = date('Y') . '/';
	$dmonth = date('m') . '/';
	$dday = date('d') . '_';
	$dhour = date ('H') . '_';            
	$dmin = date ('i') . '_';            
	$dsec = date ('s') . '_';    
	$drand = rand(0,10000);
	$root = './wp-cache/';
	if ($image) {
		$root .= 'images/';
	} else {
		$root .= 'files/';
	}
	$dir = $root . $dyear . $dmonth;
	$fullpath = $dir . $dday . $dhour . $dmin . $dsec . $drand; 
	
}    
debug('fullpath = ' . $fullpath);
$error = false;
 
if ($url == NULL) {
    echo 'get.php: can not get url';
} else {    
    /* `get new file if no in cache */
    if ($cache_rows == 0 || $force == 'true') {
    
		for ($i = 0; $i < 5; $i++) {
			/* $header_url = get_headers($url); */
			debug(get_host($url));
			$header = array();
			//$header[] = 'Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5';
			$header[] = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8';
			$header[] = 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3';
			$header[] = 'Accept-Encoding: gzip,deflate,sdch';
			//$header[] = 'Accept-Language: en-us,en;q=0.5';
			$header[] = 'Accept-Language: en-US,en;q=0.8';
			//$header[] = 'Cache-Control: max-age=0';
			$header[] = 'Cache-Control: no-cache';
			$header[] = 'Connection: keep-alive';
			$header[] = 'Keep-Alive: 300';
			$header[] = 'Host: '.get_host($url);
			//$header[] = 'Pragma: ';
			$header[] = 'Pragma: no-cache';
			$ch = curl_init(); 
			curl_setopt($ch, CURLOPT_URL, $url);
			//curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.11) Gecko/2009060215 Firefox/3.0.11 (.NET CLR 3.5.30729)');
			curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11');
			curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
			curl_setopt($ch, CURLOPT_AUTOREFERER, true); 
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
			//curl_setopt($ch, CURLOPT_ENCODING, '');
			curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate,sdch');
			curl_setopt($ch, CURLOPT_TIMEOUT, 20);
			$file = curl_exec($ch);
			curl_close ($ch);
			
			/* Collect header */
			/* $header_str = '';
			foreach ($header_url as $idx => $value) {
				$header_str .= $header_url[$idx];
			} */
			debug(strlen($file));
			/* Extract gzip  */
			/* if ((strpos($header_str, 'gzip') !== false || (strpos($file, 'title') === false) && !$image)) { */
			if ((strpos($file, '<HTML') === false) && (strpos($file, '<html') === false) && !$image) {
				$file = gzinflate(substr($file,10,-8));
			}

			if ($image)
				if (strpos($file, 'html') !== false && ((strpos($file, 'Error') !== false || strpos($file, 'Bad request') !== false)))
					continue;
			
			if ($image && strlen($file) < 1000 || (!$image) && (strlen($file) < 3000))
				continue;
			break;
        }
		
		if ($image && $i == 3) {
			echo 'get.php: error when fetch image: ' . $url . ' & ' . $force;
			$error = true;
		}
		
		if (strlen($file) < 1000) {
			echo 'get.php: file len too small: ' . $url . ' & ' . $force;
			$error = true;
		}
		
		if (strpos($file, 'not found') !== false) {
			echo 'get.php: 404 error: ' . $url . ' & ' . $force;
			$error = true;
		}
		
        /* Save image */
		if ($error == false) {
			if ($cache_rows == 0) {
				if ($image) {                    
					if (!file_exists($dir)) {
						if (mkdir($dir, 0755, true) == false) {
							echo 'get.php: can not create ' . $dir;
						} else {                                                       
							if (file_put_contents($fullpath , $file) !== false) {
								echo $fullpath; 
								mysql_query("INSERT INTO `wp_cache`(`link`, `content`, `timestamp`) VALUES ('".$url."','".$fullpath."', CURRENT_TIMESTAMP)");
							} else {
								echo 'get.php: can not write file';
							}
						}            
					} else {
						if (file_put_contents($fullpath , $file) !== false) {
							echo $fullpath;       
							mysql_query("INSERT INTO `wp_cache`(`link`, `content`, `timestamp`) VALUES ('".$url."','".$fullpath."', CURRENT_TIMESTAMP)");
						} else {
							echo 'get.php: can not write file';
						}
					}                       
				} else {
					/* `not an image */
					echo $file;                        
					//$file = str_replace("'","''" , $file);
					
					
					if (!file_exists($dir)) {
						if (mkdir($dir, 0755, true) == false) {
							//echo 'get.php: create ' . $dir;
						} else {                                   
							if (file_put_contents($fullpath , $file) !== false) {                        
								mysql_query("INSERT INTO `wp_cache`(`link`, `content`, `timestamp`) VALUES ('".$url."','".$fullpath."', CURRENT_TIMESTAMP)");
							}              
						}            
					} else {                   
						if (file_put_contents($fullpath , $file) !== false) {  
							mysql_query("INSERT INTO `wp_cache`(`link`, `content`, `timestamp`) VALUES ('".$url."','".$fullpath."', CURRENT_TIMESTAMP)");
						}
					}
				}  
			} else {
				file_put_contents($fullpath , $file);
				if ($image) {
					echo $fullpath;
				} else {
					echo $file;
				}
			}
		}
    } else {
		if ($image) {                    
            echo $fullpath;
        } else {
            $file = file_get_contents($fullpath);
            echo $file;
        }                  
    }
}

// Removing entries not updated in the last 365 days:
//mysql_query('DELETE FROM `wp_cache` WHERE `expire`<SUBTIME(NOW(),"365 0:0:0")');

?>